<?php
/**
 * ERROR CODE 0100-0199
 * 
 * */
class DB {
	private  $host = "p:127.0.0.1";
	private  $username = "root";
	private  $passwd = "";
	private  $dbname = "espms";
	private  $port = 3306;
	//private  $socket = ini_get("mysqli.default_socket");
	private  $charset = "utf8";
	
	private $mysqli;
	private $error;
	
	
	public function __construct() {
		if( empty($this->error) ) {
			if( !empty($GLOBALS['error']) ) {
				$this->error = $GLOBALS['error'];
			} else {
				$this->error = new Error();
				$GLOBALS['error'] = &$this->error;
			}
		}
		if( empty($this->mysqli) ) {
			if( !$this->connect() ) {
				throw new Exception("DB connect error",0100);
				return false;
			}
		} else {
			if( !$this->mysqli->server_version ) {
				if( !$this->connect() ) {
					throw new Exception("DB connect error",0100);
					return false;
				}
			}
		}
	}
	private function connect() {
		$this->mysqli = new mysqli( $this->host, $this->username, $this->passwd, $this->dbname, $this->port );
		if( $this->mysqli->connect_error ) {
			$this->error->setError(0100,"DB connect error ({$this->mysqli->connect_errno}) {$this->mysqli->connect_error}");
			return false;
		}
		$res = $this->mysqli->set_charset($this->charset);
		if( $res === false ) {
			$this->error->setError(0101,"DB error ({$this->mysqli->errno}) {$this->mysqli->error}");
			return false;
		}
		return true;
	}
	public function close() {
		if( !$this->mysqli->close() ) {
			$this->error->setError(0102,"DB error ({$this->mysqli->errno}) {$this->mysqli->error}");
			return false;
		}
	}
	public function query( $sql, $mode = 0, $Rmode=0 ) {
		@$this->__construct();
		$ret = null;
		$resultmode = MYSQLI_STORE_RESULT;
		if( $Rmode == 1 ) {
			$resultmode = MYSQLI_USE_RESULT;
		}
		$result = $this->mysqli->query($sql,$resultmode);
		if( $result === false ) {
			$this->error->setError(0103,"DB error ({$this->mysqli->errno}) {$this->mysqli->error} SQL = \"{$sql}\"");
			return false;
		}
		if( $result === true ) {
			return true;
		} else {
			if( $mode == 1 ) {
				$ret = $result->fetch_all(MYSQLI_ASSOC);
			} elseif( $mode == 0) {
				$ret = $result->fetch_assoc();
			}
			$result->close();
		}
		return $ret;
	}
	/*public function multiQuery( $sql ) {
	}*/
	public function lastInsertID(){
		return $this->mysqli->insert_id;
	}
}













?>